package com.jabex.manager.beans;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ValueChangeEvent;
import java.io.Serializable;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Map;

/**
 * Created by Jerges Bello on 17/08/2014.
 *
 */
@ManagedBean(name="language")
@SessionScoped
public class LanguageBean implements Serializable {

    private static final long serialVersionUID = 1L;
    static private final Locale SPANISH = new Locale("es","ES");
    static private final Locale ENGLISH = new Locale("en","GB");
    static private final Locale GERMAN = new Locale("de","DE");

    private String localeCode;
    private static Map<String,Object> countries;
    static{
	    countries = new LinkedHashMap<String,Object>();
	    countries.put("Español", SPANISH);
        countries.put("English", ENGLISH);
        countries.put("German", GERMAN);
    }

    public Map<String, Object> getCountriesInMap() {
        return countries;
    }


    public String getLocaleCode() {
        return localeCode;
    }


    public void setLocaleCode(String localeCode) {
        this.localeCode = localeCode;
    }

    //value change event listener
    public void countryLocaleCodeChanged(ValueChangeEvent e){

        String newLocaleValue = e.getNewValue().toString();

        //loop country map to compare the locale code
        for (Map.Entry<String, Object> entry : countries.entrySet()) {

            if(entry.getValue().toString().equals(newLocaleValue)){
                FacesContext.getCurrentInstance()
                        .getViewRoot().setLocale((Locale)entry.getValue());
            }
        }
    }
}
